package com.hw.service.basic;

import cn.hutool.core.img.ImgUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hw.entity.dto.basic.FoodDTO;
import com.hw.entity.dto.basic.FoodImportDTO;
import com.hw.entity.po.basic.Food;
import com.hw.entity.po.basic.StoreInfo;
import com.hw.entity.po.sys.SysUser;
import com.hw.entity.query.basic.FoodQuery;
import com.hw.entity.vo.basic.FoodVO;
import com.hw.entity.vo.basic.StoreInfoVO;
import com.hw.mapper.basic.FoodMapper;
import com.hw.model.ResponseResult;
import com.hw.utils.AdminUtils;
import com.hw.utils.ExcelUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 菜单 Service实现类
 *
 * @author whw
 * @date 2021-06-21
 */
@Service
public class FoodServiceImpl extends ServiceImpl<FoodMapper, Food> implements FoodService {

    @Autowired
    StoreInfoService storeInfoService;

    @Override
    public List<FoodVO> list(FoodQuery query) {
        QueryWrapper<Food> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("food.c_deleted", 0)
                .like(StringUtils.isNoneBlank(query.getFoodName()), "food.c_food_name", query.getFoodName())
                .like(StringUtils.isNoneBlank(query.getStoreId()), "food.c_store_id", query.getStoreId())
                .orderByAsc("food.c_price");
        //        for (FoodVO vo : pageList.getRecords()) {
//            // 处理头像
//            if (ArrayUtils.isNotEmpty(vo.getImg())) {
//                String avatarBase64 = ImgUtil.toBase64(ImgUtil.toImage(vo.getImg()), "png");
//                vo.setImgVO(avatarBase64);
//                // 一个vo带一个String的图片信息就够了，将byte[] 重复的设置为null
//                vo.setImg(null);
//            }
//        }
        return baseMapper.list(queryWrapper);
    }

    @Override
    public ResponseResult<?> save(FoodDTO dto) {
        String foodId = dto.getFoodId();
        QueryWrapper<Food> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isBlank(foodId)) {
            // 新增
            Food po = new Food();
            BeanUtils.copyProperties(dto, po);

            // 判断在同一个商家下的菜品是否重复(不同商家可能存在同名菜品)
            queryWrapper
                    .eq("c_food_name", po.getFoodName())
                    .eq("c_store_id", po.getStoreId())
                    .eq("c_deleted", 0);
            Food temp = baseMapper.selectOne(queryWrapper);

            // 若查询到同个商家，同个名字，但是菜品id不同的另一个菜，就算重复
            if (temp != null && !temp.getFoodId().equals(po.getFoodId())) {
                return ResponseResult.error("该商家已有此菜品，不可重复!");
            }
            po.setFoodId(UUID.randomUUID().toString());
            save(po);

            // 返回新增的菜品id，给图片保存
            return ResponseResult.success();
        } else {
            // 编辑
            Food food = getById(dto.getId());
            if (ObjectUtils.isNotEmpty(food)) {
                BeanUtils.copyProperties(dto, food);
            }

            // 判断在同一个商家下的菜品是否重复(不同商家可能存在同名菜品)
            queryWrapper
                    .eq("c_food_name", food.getFoodName())
                    .eq("c_store_id", food.getStoreId())
                    .eq("c_deleted", 0);
            Food temp = baseMapper.selectOne(queryWrapper);

            // 若查询到同个商家，同个名字，但是菜品id不同的另一个菜，就算重复
            if (temp != null && !temp.getFoodId().equals(food.getFoodId())) {
                return ResponseResult.error("该商家已有此菜品，不可重复!");
            }
            updateById(food);

            // 返回新增的菜品id，给图片保存
            return ResponseResult.success();
        }
    }

    /**
     * 删除
     *
     * @param foodId
     */
    @Override
    public ResponseResult<?> delete(String foodId) {
        if (StringUtils.isNotBlank(foodId)) {
            UpdateWrapper<Food> updateWrapper = new UpdateWrapper<>();
            updateWrapper
                    .set("c_deleted", 1)
                    .eq("c_food_id", foodId);
            update(updateWrapper);
            return ResponseResult.success();
        }
        return ResponseResult.error();
    }

    /**
     * 获取详情
     *
     * @param foodId
     * @return
     */
    @Override
    public FoodVO getDetail(String foodId) {
        if (StringUtils.isBlank(foodId)) {
            return null;
        }
        FoodVO vo = new FoodVO();
        QueryWrapper<Food> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("c_food_id", foodId)
                .eq("c_deleted", 0);
        Food po = getOne(queryWrapper);
        BeanUtils.copyProperties(po, vo);
        // 处理头像
//        if (ArrayUtils.isNotEmpty(po.getImg())) {
//            String avatarBase64 = ImgUtil.toBase64(ImgUtil.toImage(po.getImg()), "png");
//            vo.setImgVO(avatarBase64);
//            vo.setImg(null);
//        }
        return vo;
    }

    /**
     * 导入数据
     *
     * @param file
     * @return
     */
    @Override
    public ResponseResult<?> importData(MultipartFile file) {
        List<FoodImportDTO> resultList = ExcelUtil.fileToList(file, FoodImportDTO.class);
        if (ObjectUtils.isEmpty(resultList)) {
            return ResponseResult.error("解析数据失败");
        }

        if (CollectionUtils.isNotEmpty(resultList)) {
            List<FoodImportDTO> list = new ArrayList<>();
            for (FoodImportDTO dto : resultList) {
                Food po = new Food();
                BeanUtils.copyProperties(dto, po);

                // 获取商家
                StoreInfo tempStore = storeInfoService.getOne(new QueryWrapper<StoreInfo>()
                        .eq("c_store_name", dto.getStoreName())
                        .eq("c_deleted", 0));

                if (ObjectUtils.isEmpty(tempStore)) {
                   return ResponseResult.error("商家名字有误，请修改后导入");
                }

                po.setFoodId(UUID.randomUUID().toString());
                po.setStoreId(tempStore.getStoreId());
                po.setCount(0);

                baseMapper.insert(po);
                return ResponseResult.success();
            }
        }
        return ResponseResult.error("导入数据失败");
    }

    /**
     * 保存图片
     *
     * @param file
     * @param foodId
     */
    @Override
    public void updateAvatar(MultipartFile file, String foodId) {
        try {
            byte[] bytes = file.getBytes();
            UpdateWrapper<Food> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("c_img", bytes)
                    .eq("c_food_id", foodId);
            update(updateWrapper);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
